package com.checkbox.widgetset.client.conn;

import com.google.gwt.user.client.ui.Widget;

import com.checkbox.widgetset.SelectableTree;
import com.checkbox.widgetset.client.share.SelectableTreeState;
import com.checkbox.widgetset.client.ui.VSelectableTree;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ConnectorHierarchyChangeEvent;
import com.vaadin.client.communication.StateChangeEvent;
import com.vaadin.client.ui.AbstractComponentContainerConnector;
import com.vaadin.shared.ui.Connect;

import java.util.LinkedList;
import java.util.List;

@SuppressWarnings("serial")
@Connect(SelectableTree.class)
public class SelectableTreeConnector extends AbstractComponentContainerConnector {
  @Override
  public VSelectableTree getWidget() {
    return (VSelectableTree) super.getWidget();
  }

  @Override
  public SelectableTreeState getState() {
    return (SelectableTreeState) super.getState();
  }

  @Override
  public void updateCaption(ComponentConnector connector) {
  }

  @Override
  public void onConnectorHierarchyChange(ConnectorHierarchyChangeEvent connectorHierarchyChangeEvent) {
    List<Widget> widgets = new LinkedList<Widget>();
    for (ComponentConnector connector : this.getChildComponents()) {
      widgets.add(connector.getWidget());
    }
    getWidget().reconstruct(widgets);
  }

  @Override
  public void onStateChanged(StateChangeEvent event) {
    getWidget()
        .setExpandIcon(getState().expandIcon != null ? getState().expandIcon.getURL() : null);
    getWidget().setCollapseIcon(
        getState().collapseIcon != null ? getState().collapseIcon.getURL() : null);
    super.onStateChanged(event);
  }
}
